import { create } from 'zustand'
import { devtools } from 'zustand/middleware'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserInfo } from '@/api/login'

export const useUserStore = create(devtools(set => ({
  token: getToken(),
  userInfo: {},
  setToken: (token) => {
    if (token) {
      setToken(token)
    } else {
      removeToken()
    }
    set({ token })
  },
  // 异步方法：获取用户信息
  getUserInfo: async () => {
    try {
      const data = await getUserInfo()
      set({ userInfo: data })
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  },
  // 退出登录
  logout: () => set({ token: null, userInfo: {} }),
})))
